<?php
declare(strict_types=1);

namespace App\Model;

use Carbon\Carbon;
use Hyperf\Database\Model\SoftDeletes;

/**
 * @property int $id
 * @property int $admin_role_id
 * @property string $image_path
 * @property string $image_url
 * @property string $name
 * @property int $sex
 * @property string $sex_name
 * @property string $password_salt
 * @property string $password
 * @property string $email
 * @property string $phone
 * @property string $address
 * @property string $about_me
 * @property string $last_ip
 * @property Carbon $created_at
 * @property Carbon $updated_at
 * @property Carbon $last_login
 * @property string $deleted_at
 * @property AdminRole $admin_role
 */
class AdminUser extends MyBaseModel
{
    use SoftDeletes;

    const SEX_NAMES = [
        0 => '未知',
        1 => '男',
        2 => '女',
    ];

    const SUPER_ADMIN_ID = 1;

    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'admin_user';
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'admin_role_id',
        'image_path',
        'name',
        'sex',
        'password_salt',
        'password',
        'email',
        'phone',
        'address',
        'about_me',
        'last_login',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'id' => 'integer',
        'admin_role_id' => 'integer',
        'sex' => 'integer',
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
        'last_login' => 'datetime',
    ];

    protected $appends = [
        'image_url',
        'sex_name',
        'admin_role',
    ];

    public static function passwordVerify(string $password): bool
    {
        $pattern = '/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*?[\^\\$.*+\-?=!:|\/()\[\]{}#_~]).{6,}$/';
        return preg_match($pattern, $password) === 1;
    }

    public function getSexNameAttribute(): string
    {
        return self::SEX_NAMES[$this->sex] ?? '未知';
    }

    public function getImageUrlAttribute(): string
    {
        return self::getImageUrl($this->image_path);
    }

    public static function getImageUrl(string $imagePath, bool $withHtml = false): string
    {
        if (empty($imagePath)) {
            return '';
        }
        $url = '/admin/page/showImg?path=' . urlencode($imagePath);
        if (!$withHtml) {
            return $url;
        }
        return '<img src="' . $url . '" width="28" height="28" alt="" />';
    }

    public function getAdminRoleAttribute(): ?AdminRole
    {
        if (!$this->admin_role_id) {
            if ($this->id == self::SUPER_ADMIN_ID) {
                $adminRole = new AdminRole();
                $adminRole->name = '超级管理员';
                return $adminRole;
            }
            return null;
        }
        return AdminRole::find($this->admin_role_id);
    }
}
